<template>
	<view class="board-container">
		<view class="board">
			<canvas class="board-canvas" canvas-id="drawCanvas" disable-scroll="true" @touchstart="touchStart"
				@touchmove="touchMove" @touchend="touchEnd"></canvas>

			<view class="flex spacea center plt10" style="width: 100%; background: aliceblue;">
				<button class="mini-btn" type="warn" @click="back" size="mini">撤销</button>
				<button class="mini-btn" type="warn" @click="agin" size="mini">重签</button>
				<button class="mini-btn" type="primary" size="mini" @click="saveImage">保存</button>
			</view>
		</view>

	</view>
</template>

<script>
	import urlsa from '@/siteinfo.js';

	function deepClone(data) {
		return JSON.parse(JSON.stringify(data))
	}
	export default {
		data() {
			return {
				curDrawArr: [],
				startX: 0,
				startY: 0,
				ctx: {},
				currentColor: '#091A22',
				begin: false,
				bgColor: 'white', //背景色
				base_url:"",
				lineWidth: 4, //画笔宽度
				penMode: true, //打开画笔  开关
				url: "",
				currentTab: 1,
				currentIndex: 0,
				selectPointer: [], //所有选中的线

				cache: "",
				points: [],


				//start 上传图片  参数 换成自己接口需要的
				action: '',
				formdata: {
					dir: 'patient',
					type: 'image'
				},
				header: {
					Authorization: "Bearer " + uni.getStorageSync('token')
				},
				// end 上传图片  参数


			}
		},
		onLoad() {
			var that = this;
			that.global.request.post({
				data: {
					do: 'base',
			
				},
				success: res => {
					that.base_url = res.contract
				}
			})
			
			this.action = this.http + '/api/common/upload'

		},
		created() {},
		mounted() {
			var that = this;
			that.global.request.post({
				data: {
					do: 'shop_info',
			
				},
				success: res => {
					if(res.contract != '')
					{
						that.url = res.contract;
						that.ctx = uni.createCanvasContext('drawCanvas', that);
						that.initBoard();
						that.fillWelcomeBackground(that.ctx);
						
						that.cache = new Map()
						that.ctx.setLineWidth(that.lineWidth);
					}else{
						that.global.request.post({
							data: {
								do: 'base',
						
							},
							success: ress => {
								that.url = ress.contract;
								that.base_url = ress.contract
								that.ctx = uni.createCanvasContext('drawCanvas', that);
								that.initBoard();
								that.fillWelcomeBackground(that.ctx);
								
								that.cache = new Map()
								that.ctx.setLineWidth(that.lineWidth);
							}
						})
					}
					
				}
			})
			
		},
		methods: {
			agin(){
				var that = this;
				
				that.url = that.base_url
				that.ctx = uni.createCanvasContext('drawCanvas', that);
				that.initBoard();
				that.fillWelcomeBackground(that.ctx);
				
				that.cache = new Map()
				that.ctx.setLineWidth(that.lineWidth);
			},
			initBoard() {
				this.ctx.setLineCap('round') // 让线条圆润
				this.ctx.strokeStyle = this.currentColor;
				this.ctx.setLineWidth(this.lineWidth);
			},
			/**
			 * 临时保存画布上的数据
			 * @param {Any} key 用于访问的key
			 * @param {Boolean} isInit 保存完毕后是否清空画布，默认为true
			 */
			saveCache(key, isInit = true) {
				const {
					cache,
					selectPointer
				} = this
				const temp = deepClone(selectPointer)
				cache.set(key, temp)
				if (isInit) this.fillBackground(this.ctx, 1);
			},

			/**
			 * 用缓存的key恢复画布
			 * @param {Any} key 用于访问的key
			 */
			restoreCache(key) {
				const {
					drawByData,
					cache
				} = this
				if (cache.get(key)) {
					this.selectPointer = cache.get(key)
					drawByData(this.selectPointer)
				} else {
					this.fillBackground(this.ctx, 2);
				}
			},
			/**
			 * 根据传入的数据绘制
			 * @param {Array} data
			 */
			drawByData(data, value) {
				let page = this
				const {
					ctx
				} = this
				if (!data || !data.length) {
					return this.fillBackground(ctx, 3)
				} else {
					const tempData = deepClone(data)
					let dats = []
					tempData.forEach(f => {
						if (f.length <= 1) {
							const pos = f[0]
							ctx.moveTo(pos[0], pos[1])
							ctx.lineTo(pos[0], pos[1])
						} else {
							dats.push(f)
						}
					})
					while (!!dats.length) {
						const lineData = dats.shift()
						ctx.moveTo(...lineData.shift())
						while (!!lineData.length) {
							ctx.lineTo(...lineData.shift())
						}
					}
					// #ifdef  APP-PLUS
					if (value == 'back') {
						this.fillWelcomeBackground(this.ctx);
					}
					// #endif

					this.fillWelcomeBackground(this.ctx);

				}

			},
			// 撤销
			back() {
				const {
					selectPointer,
					drawByData
				} = this
				selectPointer.pop()
				drawByData(selectPointer, 'back')
			},
			// 保存 图片数据  到患者影像中
			saveImage() {
				let page = this
				uni.canvasToTempFilePath({
					canvasId: 'drawCanvas',
					success: function(res) {
						// 在H5平台下，tempFilePath 为 base64
						page.uploadimage(res.tempFilePath)
					}
				})
			},
			// 上传  图片
			uploadimage(val) {
				var that = this;
				var token = uni.getStorageSync("token");
				uni.uploadFile({
					header: {
						'token': token,
						// "Content-Type": 'application/x-www-form-urlencoded', // 默认值
						// 'X-TOKEN-PETMALL': '', 
					},
					url: urlsa.siteroot + '/app/index.php?op=reg&i=' + urlsa.uniacid +
						'&c=entry&m=lh_shop&v=1&do=upload_img', //仅为示例，非真实的接口地址
					filePath: val,
					name: 'upfile',
					success: (uploadFileRes) => {
						var contract = JSON.parse(uploadFileRes.data).datas
						that.global.request.post({
							data: {
								do: 'upLoad_contract',
								s_id:wx.getStorageSync('s_ids'),
								contract:contract
							},
							success: res => {
								uni.showToast({
									title:res.message
								})
								setTimeout(function(){
									uni.navigateBack({
										
									})
								},500)
								
							}
						})
						
					},
				});
			},
			// 绘画 开始
			touchStart(e) {
				// customPrint('我能够进行绘制');
				if (this.penMode) {
					this.lineBegin(e.touches[0].x, e.touches[0].y)
					this.lineAddPoint(e.touches[0].x, e.touches[0].y);
					this.draw(true);
				}
				this.curDrawArr.push({
					x: e.touches[0].x,
					y: e.touches[0].y
				});
				this.points.push([e.touches[0].x, e.touches[0].y])
				this.selectPointer.push([
					[e.touches[0].x, e.touches[0].y]
				])

			},
			// 绘画 移动
			touchMove(e) {
				if (this.begin) {
					if (this.penMode) {
						this.lineAddPoint(e.touches[0].x, e.touches[0].y);
						this.draw(true);
					}
					this.curDrawArr.push({
						x: e.touches[0].x,
						y: e.touches[0].y
					});
					this.points.push([e.touches[0].x, e.touches[0].y])
					this.selectPointer[this.selectPointer.length - 1].push([e.touches[0].x, e.touches[0].y])

				}
			},
			// 绘画 结束
			touchEnd(e) {
				if (this.penMode) {
					this.curDrawArr = [];
					this.points = []
					this.lineEnd();
				}
			},
			// 绘画
			hollowRectBegin(x, y) {
				this.begin = true;
				this.ctx.beginPath()
				this.startX = x;
				this.startY = y;
			},

			// 开始绘制线条
			lineBegin: function(x, y) {
				this.begin = true;
				this.ctx.beginPath()
				this.startX = x;
				this.startY = y;
				this.ctx.moveTo(this.startX, this.startY)
				this.lineAddPoint(x, y);
			},
			// 绘制线条中间添加点
			lineAddPoint: function(x, y) {
				this.ctx.moveTo(this.startX, this.startY)
				this.ctx.lineTo(x, y);
				this.ctx.stroke();
				this.startX = x;
				this.startY = y;
				let pointer = []
				pointer.push({
					x,
					y
				})
			},
			// 绘制线条结束
			lineEnd: function() {
				this.ctx.closePath();
				this.begin = false;
			},
			// canvas上下文设置背景为白色   清除  重置 背景色
			fillBackground: function(context, length) {
				let page = this
				const query = uni.createSelectorQuery().in(this);
				query.select('.board').boundingClientRect(data => {
					uni.getImageInfo({
						src:page.url,
						success:function(res)
						{
							var img = res.path;
							
							context.setFillStyle(this.bgColor); //设置填充色，如果没有设置 fillStyle，默认颜色为 black。
							context.fillRect(0, 0, data.width, (data.height) - 50) //TODO context的宽和高待定
							context.fill();
							context.drawImage(img, 0, 0, data.width, (data.height) -
								50)
							
							context.setFillStyle('rgba(230,162,60,.16)');
							context.setFontSize(18);
							context.setTextAlign('center');
							
							context.stroke()
							context.draw();
							
							if (length == 2 || length == 3) {
								page.selectPointer = []
							}
						}
					})
					


				}).exec();
			},
			// canvas上下文设置背景为白色  默认  设置  背景色  背景图片  文字 等
			fillWelcomeBackground: function(context) {
				let page = this
				const query = uni.createSelectorQuery().in(this); // 获取页面上节点

				query.select('.board').boundingClientRect(data => {
					uni.getImageInfo({
						src:page.url,
						success:function(res)
						{
							var img = res.path;
							
							context.setFillStyle(page.bgColor); //设置填充色，如果没有设置 fillStyle，默认颜色为 black。
							context.fillRect(0, 0, data.width, (data.height) - 100) //TODO context的宽和高待定
							context.fill();
							context.drawImage(img, 0, 0, data.width, (data.height) -
								50)
							
							context.setFillStyle('rgba(230,162,60,.16)');
							context.setFontSize(18);
							context.setTextAlign('center');
							
							
							context.stroke()
							context.draw();
						}
					})
					

				}).exec();
			},
			// 绘制canvas
			// isReverse: 是否保留之前的像素
			draw: function(isReverse = false, cb) {
				this.ctx.draw(isReverse, () => {
					if (cb && typeof(cb) == "function") {
						cb();
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.board-container {
		height: 100%;
		width: 100%;

		.board {
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			transform: translateY(0);
			display: block;

			.board-canvas {
				width: 100%;
				height: calc(100% - 70px);
				margin: 0 auto;
				z-index: 100;
			}

		}
	}
</style>
